#pragma once

#include "pch.h"
#include "UdpClient.h"

struct UdpSocket
{
    uint64_t sock;

    struct Desc
    {
        unsigned int af = AF_INET;

        unsigned int type = SOCK_DGRAM;
        unsigned int protocol = IPPROTO_UDP;

    };

    bool Create(const Desc &desc);

    void Close();

    template <typename T>
    int RecvFrom(T &revbuf, const struct sockaddr_in &soserver)
    {
        static int addrlen = sizeof(struct sockaddr_in);
        return recvfrom(sock, (char *)&revbuf, sizeof(revbuf), 0, (sockaddr*)&soserver, &addrlen);
    }


    template <typename T>
    int SendTo(const T &senbuf, const struct sockaddr_in &soserver)
    {
        static int addrlen = sizeof(struct sockaddr_in);
        return sendto(sock, (const char *)&senbuf, sizeof(senbuf), 0, (sockaddr*)&soserver, addrlen);
    }

    template <typename T>
    int SendTo(const T &senbuf, const char *host, unsigned int port)
    {
        sockaddr_in soserver;
        soserver.sin_family = AF_INET;
        soserver.sin_addr.s_addr = inet_addr(host);
        soserver.sin_port = htons(port);

        return SendTo<T>(senbuf, soserver);
    }
    template <typename T>
    int SendTo(const T &senbuf, const UdpClient& client)
    {
        return SendTo<T>(senbuf, client.clientAddr);
    }
};